<template>
	<view class="shared-cart-container">
		<view class="page-header">
			<text class="page-title">分享的货盘</text>
			<text class="share-time" v-if="shareInfo.shareTime">分享于 {{shareInfo.shareTime}}</text>
		</view>
		
		<view class="cart-list" v-if="cartItems.length > 0">
			<view class="cart-item" v-for="(item, index) in cartItems" :key="index">
				<image :src="item.product.preview_image_url || '/static/empty-image.png'" mode="aspectFit" class="item-image" @tap="previewImage(item.product.preview_image_url)"></image>
				<view class="item-info" @tap="navigateToProduct(item)">
					<text class="item-name">{{item.product.name}}</text>
					<view class="item-sku" v-if="item.skuCode">
						<text class="sku-label">规格：</text>
						<text class="sku-value">{{item.skuCode}}</text>
					</view>
					<text class="item-price">¥{{item.salePrice || item.price}}</text>
				</view>
			</view>
		</view>
		<view class="empty-cart" v-else>
			<image src="/static/empty-cart.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">分享的货盘为空</text>
		</view>
		
		<view class="total-section" v-if="cartItems.length > 0">
			<view class="divider"></view>
			<view class="total-row">
				<text class="total-label">合计：</text>
				<text class="total-price">¥{{totalPrice}}</text>
			</view>
		</view>
		
		<!-- 返回首页按钮 
		
		<view class="action-buttons">
			<button class="action-btn add-to-cart-btn" @tap="addToMyCart">添加到我的货盘</button>
			<button class="action-btn place-order-btn" @tap="placeOrder">直接下单</button>
		</view>
		
		-->
		
		
		<!-- 加载中提示 -->
		<uni-popup ref="loadingPopup" type="center" :mask-click="false">
			<view class="loading-box">
				<view class="loading-spinner"></view>
				<text class="loading-text">{{loadingText}}</text>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { cartApi } from '../../api/index.js';
	import config from '../../utils/config.js';
	
	export default {
		data() {
			return {
				shareId: '', // 分享ID
				shareInfo: {
					sharedBy: '', // 分享人
					shareTime: '' // 分享时间
				},
				cartItems: [], // 分享的货盘商品
				loadingText: '加载中...',
				isDataLoaded: false // 添加标志来防止重复加载
			}
		},
		computed: {
			totalPrice() {
				return this.cartItems.reduce((total, item) => {
					return total + (item.salePrice || item.price || 0)
				}, 0).toFixed(2)
			}
		},
		onLoad(options) {
			// 从分享链接中获取分享ID
			console.log('Shared cart page loading with options:', options);
			
			// 检查是否是从分享打开的
			if (options.scene) {
				console.log('Opening from share scene:', options.scene);
			}
			
			if (options.shareId) {
				this.shareId = options.shareId;
				// 只有当数据未加载时才加载
				if (!this.isDataLoaded) {
					this.getSharedCartDetails(options.shareId);
				}
			} else {
				uni.showToast({
					title: '分享信息不存在',
					icon: 'none'
				});
			}
		},
		// 页面再次显示时，如有必要进行刷新
		
		// onShow() {
		// 	console.log('Shared cart page showing');
		// 	// 如果已经有shareId但数据未加载，则加载数据
		// 	if (this.shareId && !this.isDataLoaded && this.cartItems.length === 0) {
		// 		console.log('Reloading shared cart data');
		// 		this.getSharedCartDetails(this.shareId);
		// 	}
		// },

		// 页面隐藏时，根据情况重置标志
		onHide() {
			console.log('Shared cart page hiding');
			// 如果我们是通过返回按钮离开，不重置
			// 但如果是通过跳转到其他页面离开，可以考虑重置
			// 这里暂时保留标志，避免重复加载
		},
		// 页面卸载时重置标志
		onUnload() {
			console.log('Shared cart page unloading');
			// 页面卸载时，重置加载标志，以便下次导航正常加载
			this.isDataLoaded = false;
		},
		// 小程序分享功能
		onShareAppMessage() {
			return {
				title: `查看分享的珠宝货盘 (${this.cartItems.length}件商品)`,
				path: `/pages/cart/shared-cart?shareId=${this.shareId}`,
				imageUrl: this.cartItems.length > 0 ? this.cartItems[0].product.preview_image_url : '/static/share-default.png'
			}
		},
		
		// 分享到朋友圈
		onShareTimeline() {
			return {
				title: `珠宝货盘分享 (${this.cartItems.length}件商品)`,
				query: `shareId=${this.shareId}`,
				imageUrl: this.cartItems.length > 0 ? this.cartItems[0].product.preview_image_url : '/static/share-default.png'
			}
		},
		
		methods: {
			// 获取分享货盘详情
			async getSharedCartDetails(shareId) {
				console.log('Loading shared cart details for ID:', shareId);
				// 防止重复加载
				if (this.isDataLoaded && this.cartItems.length > 0) {
					console.log('Data already loaded, skipping');
					return;
				}
				
				this.loadingText = '加载分享内容...';
				this.$refs.loadingPopup.open();
				
				try {
					// 调用API获取分享货盘详情
					const result = await cartApi.getSharedCartDetails(shareId);
					if (result && result.data) {
						const shareData = result.data;
						
						// 设置分享信息
						this.shareInfo = {
							sharedBy: shareData.sharedBy || '珠宝商',
							shareTime: shareData.shareTime || new Date().toLocaleString()
						};
						
						// 设置货盘商品
						this.cartItems = shareData.items || [];
						// 标记数据已加载
						this.isDataLoaded = true;
					} else {
						throw new Error('获取分享内容失败');
					}
					
					this.$refs.loadingPopup.close();
				} catch (error) {
					console.error('获取分享货盘详情失败', error);
					this.$refs.loadingPopup.close();
					
					uni.showToast({
						title: error.message || '获取分享内容失败',
						icon: 'none'
					});
				}
			},
			
			// 添加到我的货盘
			async addToMyCart() {
				if (this.cartItems.length === 0) {
					uni.showToast({
						title: '货盘为空，无法添加',
						icon: 'none'
					});
					return;
				}
				
				this.loadingText = '添加到货盘...';
				this.$refs.loadingPopup.open();
				
				try {
					// 调用API添加到我的货盘
					const result = await cartApi.addSharedItemsToCart({
						shareId: this.shareId
					});
					
					this.$refs.loadingPopup.close();
					
					if (result && result.data) {
						uni.showToast({
							title: '已添加到货盘',
							icon: 'success',
							success: () => {
								setTimeout(() => {
									// 跳转到我的货盘页面
									uni.switchTab({
										url: '/pages/cart/cart'
									});
								}, 1000);
							}
						});
					} else {
						throw new Error('添加到货盘失败');
					}
				} catch (error) {
					this.$refs.loadingPopup.close();
					uni.showToast({
						title: error.message || '添加失败',
						icon: 'none'
					});
				}
			},
			
			// 直接下单
			async placeOrder() {
				if (this.cartItems.length === 0) {
					uni.showToast({
						title: '货盘为空，无法下单',
						icon: 'none'
					});
					return;
				}
				
				// 提示用户填写备注信息
				uni.showModal({
					title: '填写订单备注',
					editable: true,
					placeholderText: '请输入您的特殊需求或备注信息',
					success: async (res) => {
						if (res.confirm) {
							const remarks = res.content || '';
							
							this.loadingText = '正在提交订单...';
							this.$refs.loadingPopup.open();
							
							try {
								// 调用下单API
								const result = await cartApi.placeOrderFromShare({
									shareId: this.shareId,
									remarks: remarks
								});
								
								this.$refs.loadingPopup.close();
								
								if (result && result.data && result.data.orderId) {
									const orderId = result.data.orderId;
									
									uni.showToast({
										title: '订单已提交',
										icon: 'success',
										success: () => {
											// 跳转到订单确认页
											setTimeout(() => {
												uni.navigateTo({
													url: `/pages/order/confirmation?orderId=${orderId}`
												});
											}, 1000);
										}
									});
								} else {
									throw new Error('提交订单失败');
								}
							} catch (error) {
								this.$refs.loadingPopup.close();
								uni.showToast({
									title: error.message || '下单失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 返回首页
			backToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},
			
			// 预览图片
			previewImage(imageUrl) {
				if (!imageUrl) return;
				
				uni.previewImage({
					urls: [imageUrl],
					current: imageUrl
				});
			},
			
			// 导航到产品详情页
			navigateToProduct(item) {
				if (!item) return;
				console.log(item)
				
				uni.navigateTo({
					url: `/pages/product/detail?id=${item.product.id}&skucode=${item.skuCode}`
				});
			},
			
			// 获取应用基础URL
			getAppBaseUrl() {
				const apiUrl = config.baseUrl;
				// 提取域名 (例如 http://example.com/api 变为 http://example.com)
				const domainMatch = apiUrl.match(/(https?:\/\/[^\/]+)/);
				if (domainMatch && domainMatch[1]) {
					return domainMatch[1];
				}
			}
		}
	}
</script>

<style>
	.shared-cart-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 150rpx;
	}
	
	.page-header {
		background-color: #fff;
		padding: 30rpx;
		text-align: center;
		box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
		margin-bottom: 20rpx;
	}
	
	.page-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}
	
	.share-info {
		font-size: 24rpx;
		color: #999;
	}
	
	.share-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.cart-list {
		padding: 20rpx;
	}
	
	.cart-item {
		display: flex;
		align-items: center;
		background-color: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
		position: relative;
		box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
	}
	
	.item-image {
		width: 160rpx;
		height: 160rpx;
		margin: 0 20rpx;
		border-radius: 8rpx;
		border: 1px solid #eee;
	}
	
	.item-info {
		flex: 1;
		padding-right: 10rpx;
	}
	
	.item-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.item-sku {
		display: flex;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	
	.sku-label {
		color: #999;
	}
	
	.sku-value {
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.item-price {
		font-size: 32rpx;
		color: #F3B250;
		font-weight: bold;
	}
	
	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 200rpx;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 30rpx;
	}
	
	.total-section {
		padding: 20rpx 30rpx;
		background-color: #fff;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
	}
	
	.divider {
		height: 1px;
		background-color: #eee;
		margin-bottom: 20rpx;
	}
	
	.total-row {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	
	.total-label {
		font-size: 30rpx;
		color: #333;
	}
	
	.total-price {
		font-size: 36rpx;
		color: #F3B250;
		font-weight: bold;
	}
	
	.action-buttons {
		display: flex;
		justify-content: space-around;
		padding: 20rpx;
		background-color: #fff;
		position: fixed;
		bottom: 70rpx;
		left: 0;
		right: 0;
		z-index: 9;
		box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	}
	
	.action-btn {
		width: 45%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: bold;
	}
	
	.add-to-cart-btn {
		background-color: #fff;
		color: #F3B250;
		border: 2rpx solid #F3B250;
	}
	
	.place-order-btn {
		background-color: #F3B250;
		color: #fff;
	}
	
	.share-button {
		position: fixed;
		bottom: 70rpx;
		right: 30rpx;
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		background-color: #F3B250;
		color: #fff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.1);
		z-index: 10;
		padding: 0;
	}
	
	.share-icon {
		font-size: 40rpx;
		margin-bottom: 8rpx;
	}
	
	.back-home-btn {
		position: fixed;
		bottom: 10rpx;
		left: 50%;
		transform: translateX(-50%);
		width: 200rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		font-size: 24rpx;
		color: #999;
		background: none;
		border: none;
	}
	
	/* 加载弹窗样式 */
	.loading-box {
		background-color: rgba(0, 0, 0, 0.7);
		border-radius: 10rpx;
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 200rpx;
	}
	
	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #F3B250;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}
	
	.loading-text {
		color: #fff;
		font-size: 24rpx;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
</style> 